import { useState, useCallback } from 'react';
import { exceptSpace } from '@/utils/utils';
import useRefState from './useRefState';

export default function useMakeList({ fetchList }) {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // --- 列表请求参数 ---
  const [paginationRef, setPagination] = useRefState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // --- 额外的参数，通常是表单元素的值 ---
  const [extraParamsRef, setExtraParams] = useRefState({});

  // --- 列表 ---
  const [list, setList] = useState([]);

  // --- loading状态 ---
  const [loading, setLoading] = useState(false);

  // --- 处理请求参数 ---
  const getQueryParams = useCallback(
    () =>
      exceptSpace({
        ...extraParamsRef.current,
        pageNum: paginationRef.current.current || 1,
        pageSize: paginationRef.current.pageSize || 10,
      }),
    [extraParamsRef, paginationRef],
  );

  // --- 获取表格数据 ---
  const getList = useCallback(() => {
    setLoading(true);
    fetchList(getQueryParams())
      .then(res => {
        if (res.success) {
          setPagination(prev => ({ ...prev, total: res?.data?.total || 0 }));
          const { pageSize = 10, current = 1 } = paginationRef.current;
          setList(
            res?.data?.records?.map((item, index) => ({
              ...item,
              __index: (current - 1) * pageSize + index + 1,
            })) || [],
          );
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [getQueryParams, setPagination, paginationRef]);

  return {
    selectedRowKeys,
    setSelectedRowKeys,
    pagination: paginationRef.current,
    setPagination,
    extraParams: extraParamsRef.current,
    setExtraParams,
    list,
    setList,
    getList,
    loading,
    setLoading,
  };
}
